package pl.polsl.mmm.projectcomm;


import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.MobileAnarchy.Android.Widgets.Joystick.JoystickMovedListener;
import com.MobileAnarchy.Android.Widgets.Joystick.JoystickView;

import java.io.ByteArrayInputStream;

import pl.polsl.mmm.projectcomm.input.button.Button;
import pl.polsl.mmm.projectcomm.input.button.ButtonClickedListener;
import pl.polsl.mmm.projectcomm.objects.ModelBob;
import pl.polsl.mmm.projectcomm.objects.state.BobState;
import pl.polsl.mmm.projectcomm.util.bluetooth.AcceptThread;
import pl.polsl.mmm.projectcomm.util.bluetooth.ConnectThread;
import pl.polsl.mmm.projectcomm.util.bluetooth.ConnectedThread;

public class GameActivity extends Activity {
	private GLSurfaceView glSurfaceView;
    private JoystickView joystick;
    private Button oneHandBtn, twoHandsBtn;
    private android.widget.Button jumpBtn;
    private boolean rendererSet = false;
    private final GameRenderer gameRenderer = new GameRenderer(this);
    public int tilt, pan;
    GameActivity me;

    private final Handler handler = new Handler() {

        public void handleMessage(Message msg) {

            byte[] byteArray = msg.getData().getByteArray("byteArray");
            BobState bobState = BobState.createFromByteArray(byteArray);
            gameRenderer.setBob2Params(bobState);
        }
    };

    // Wysłanie danych boba2 przez bluetooth
    public void sendBob(ModelBob modelBob) {

        // Przekształcenie danych o modelu do tablicy bajtów
        byte[] data = modelBob.getBobState().getByteArray();

        // Wysłanie przez bluetooth
        AcceptThread.write(data);
        ConnectThread.write(data);
    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        //włączenie fullscreena
        /* requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

        ConnectedThread.setGameHandler(handler);

        setContentView(R.layout.activity_game);
        me = this;

		glSurfaceView = (GLSurfaceView)findViewById(R.id.openglview);
        joystick = (JoystickView)findViewById(R.id.joystickView);
        oneHandBtn = (Button)findViewById(R.id.oneHandBtn);
        twoHandsBtn = (Button)findViewById(R.id.twoHandsBtn);
        jumpBtn = (android.widget.Button)findViewById(R.id.jumpBtn);

        final ActivityManager activityManager =
				(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		
		final ConfigurationInfo configurationInfo =
				activityManager.getDeviceConfigurationInfo();
		
		final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000 || //sprawdzenie czy urzadzenie posiada OpenGL ES 2.0
				 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 // ominiecie buga zwiazanego z emulatorem
				 && (Build.FINGERPRINT.startsWith("generic")
						 || Build.FINGERPRINT.startsWith("unknown")
						 || Build.MODEL.contains("google_sdk")
						 || Build.MODEL.contains("Emulator")
						 || Build.MODEL.contains("Android SDK built for x86")));
		
		if (supportsEs2) {
			glSurfaceView.setEGLContextClientVersion(2);
			glSurfaceView.setRenderer(gameRenderer);
			rendererSet = true;
		} else {
			Toast.makeText(this, "Trolololo, to urzadzenie nie posiada OpenGL ES 2.0!", Toast.LENGTH_LONG).show();
			return;
		}

        // Ustawienie listenerów przycisków
        joystick.setOnJostickMovedListener(joystickListener);
        oneHandBtn.setOnButtonClickedListener(oneHandBtnListener);
        twoHandsBtn.setOnButtonClickedListener(twoHandsBtnListener);
        jumpBtn.setOnTouchListener(jumpBtnListener);

        // Ustawienie bitmap przycisków
        oneHandBtn.setNormalBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.one_hand_red));
        oneHandBtn.setPressedBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.one_hand_green));
        twoHandsBtn.setNormalBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.two_hands_red));
        twoHandsBtn.setPressedBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.two_hands_green));
		glSurfaceView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event != null) {
					final float normalizedX = (event.getX()/ (float) v.getWidth()) * 2 - 1;
					final float normalizedY = -((event.getY()/ (float) v.getHeight()) *2 - 1);
					/*if(event.getAction() == MotionEvent.ACTION_DOWN) {

						glSurfaceView.queueEvent(new Runnable() {
							@Override
							public void run() {
                                gameRenderer.handleTouchPress(normalizedX, normalizedY);
							}
						});
					}
                    else*/ if (event.getAction() == MotionEvent.ACTION_MOVE) {
						glSurfaceView.queueEvent(new Runnable() {
							@Override
							public void run() {
                                gameRenderer.handleTouchDrag(normalizedX, normalizedY);
							}
						});
					}
					return true;
				} else {
					return false;
				}
			}
		});

	}

    // Nasłuchiwanie ruchu joysticka
    public JoystickMovedListener joystickListener = new JoystickMovedListener() {

        @Override
        public void OnMoved(int newPan, int newTilt) {
            gameRenderer.setPan(newPan);
            gameRenderer.setTilt(newTilt);
        }

        @Override
        public void OnReleased() {

        }

        public void OnReturnedToCenter() {
        }
    };

    // Listener przycisku jednej ręki
    public ButtonClickedListener oneHandBtnListener = new ButtonClickedListener() {

        @Override
        public void OnClicked() {

            if (oneHandBtn.getState()) {
                gameRenderer.setGestureState(Constants.Gestures.ONE_HAND);
                twoHandsBtn.setState(false);
            } else {
                gameRenderer.setGestureState(Constants.Gestures.NO_GESTURES);
            }
        }
    };

    // Listener przycisku dwóch rąk
    public ButtonClickedListener twoHandsBtnListener = new ButtonClickedListener() {

        @Override
        public void OnClicked() {

            if (twoHandsBtn.getState()) {
                gameRenderer.setGestureState(Constants.Gestures.TWO_HANDS);
                oneHandBtn.setState(false);
            } else {
                gameRenderer.setGestureState(Constants.Gestures.NO_GESTURES);
            }
        }
    };

    // Listener przycisku skoku
    public View.OnTouchListener jumpBtnListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                gameRenderer.startJump();
                jumpBtn.setBackgroundResource(R.drawable.jump_pressed);
            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                jumpBtn.setBackgroundResource(R.drawable.jump);
            }
            return true;
        }
    };

    @Override
	protected void onPause() {
		super.onPause();

		if(rendererSet) {
			glSurfaceView.onPause();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();

		if(rendererSet) {
			glSurfaceView.onResume();
		}
	}
}
